package com.yb0os1.storefront.controller;


import com.yb0os1.Yb0os1Plugin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.net.URLClassLoader;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@RestController
public class TestController {
    private Yb0os1Plugin countPlugin;
    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @GetMapping("/time")
    public String getTime() {
        if (countPlugin != null) {
            countPlugin.beforeGetTime();
        }
        return LocalDateTime.now().format(formatter);
    }

    @GetMapping("/load/{path}")
    public String load(@PathVariable("path") String path) {
        try {
            File file = new File(path);
            URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{file.toURI().toURL()});
            InputStream yb0os1Plugin = urlClassLoader.getResourceAsStream("yb0os1.plugin");
            String myPluginFullClassName = new String(yb0os1Plugin.readAllBytes());
            Class<?> aClass = urlClassLoader.loadClass(myPluginFullClassName);
            Constructor<?> constructor = aClass.getConstructor();
            countPlugin = (Yb0os1Plugin) constructor.newInstance();
            return "加载成功"+aClass.getName();
        } catch (Exception e) {
            return "加载失败";
        }
    }
}
